package cn.heygod.graywhale.test.controller;

import cn.heygod.graywhale.runtime.context.Input;
import cn.heygod.graywhale.runtime.context.Output;
import cn.heygod.graywhale.runtime.task.TaskFlowService;
import cn.heygod.graywhale.runtime.task.def.TaskDefineManager;
import cn.heygod.graywhale.runtime.task.def.TaskFlowDef;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @className: TaskFlowTestController
 * @author: Simon
 * @description: TODO
 * @date: 2023/11/28 0:04
 * @version: 1.0
 */
@RestController
@RequestMapping("/gw-test/task-flow")
public class TaskFlowTestController {

    @Autowired
    private TaskDefineManager  taskDefineManager;

    @Autowired
    private TaskFlowService taskFlowService;


    @GetMapping("/init-test-def")
    @ResponseBody
    public String initTestDef() throws IOException {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("test-flow-def.json");

        String jsonStr =  IOUtils.toString(inputStream,"UTF-8");
        List<TaskFlowDef> flows = JSONUtil.toList(jsonStr, TaskFlowDef.class  );

        flows.stream().forEach(flowDef -> {
            taskDefineManager.addFlow(flowDef);
        });
        return "init finish";
    }

    @GetMapping("/flow/def")
    @ResponseBody
    public TaskFlowDef getFlowDef(@RequestParam("id") String id) throws IOException {
        return taskDefineManager.getFlow(id);
    }

    @GetMapping("/flow/start")
    @ResponseBody
    public Output getFlowStart(@RequestParam("id") String id, @RequestBody String body) throws IOException {
        Input input = new Input();
        input.setId(IdUtil.getSnowflakeNextIdStr());
        input.setBody(body);
        return taskFlowService.start(id,input);
    }
}
